package com.topvision.auth.security;

import com.topvision.auth.domain.SysUser;
import com.topvision.auth.domain.SysUserAccount;
import com.topvision.auth.repository.SysUserAccountRepository;
import com.topvision.auth.repository.SysUserRepository;
import com.topvision.common.security.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 */
//@Service("userDetailsService")
@Slf4j
public class DomainUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private SysUserAccountRepository sysUserAccountRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUserAccount account  = sysUserAccountRepository.findOneByAccount(username);

        Optional<SysUser> realUser = sysUserRepository.findOneWithRolesById(account.getUserId());



        return realUser.map(user -> {
            Set<GrantedAuthority> grantedAuthorities = user.getAuthorities();
            return new UserInfo(user.getId(), account.getAccount(), account.getPassword(),true, grantedAuthorities,user.getUsername(), user.getMobile(), user.getEmail());
        }).orElseThrow(() -> new UsernameNotFoundException("用户" + username + "不存在!"));
    }
}